package com.jakewharton.rxbinding2.widget;

import io.reactivex.Observable;
import io.reactivex.Observer;
import io.reactivex.ohos.MainThreadDisposable;
import io.reactivex.functions.Predicate;
import ohos.agp.components.Text;

import static com.jakewharton.rxbinding2.internal.Preconditions.checkMainThread;

final class TextEditorActionObservable extends Observable<Integer> {
  private final Text view;
  private final Predicate<? super Integer> handled;

  TextEditorActionObservable(Text view, Predicate<? super Integer> handled) {
    this.view = view;
    this.handled = handled;
  }

  @Override
  protected void subscribeActual(Observer<? super Integer> observer) {
    if (!checkMainThread(observer)) {
      return;
    }
    Listener listener = new Listener(view, observer, handled);
    observer.onSubscribe(listener);
    view.setEditorActionListener(listener);
  }

  static final class Listener extends MainThreadDisposable implements Text.EditorActionListener {
    private final Text view;
    private final Observer<? super Integer> observer;
    private final Predicate<? super Integer> handled;

    Listener(Text view, Observer<? super Integer> observer,
        Predicate<? super Integer> handled) {
      this.view = view;
      this.observer = observer;
      this.handled = handled;
    }

    @Override
    protected void onDispose() {
      view.setEditorActionListener(null);
    }

    @Override
    public boolean onTextEditorAction(int actionId) {
      try {
        if (!isDisposed() && handled.test(actionId)) {
          observer.onNext(actionId);
          return true;
        }
      } catch (Exception e) {
        observer.onError(e);
        dispose();
      }
      return false;
    }
  }
}
